﻿namespace EyeOpen.DataEntry.Web.Mvc
{
	using System;
	using System.Web.Mvc;
	using System.Web.Routing;

	using EyeOpen.DataEntry.Data;
	using EyeOpen.DataEntry.Domain;
	using EyeOpen.Web.Mvc;

	public class DataEntryHttpModule : HttpModule
	{
		protected override void RegisterCustomRoutes(RouteCollection routes)
		{
			routes
				.MapRoute(
					"Default",
					"{controller}/{action}/{id}",
					new { controller = "Customer", action = "List", id = UrlParameter.Optional });
		}

		protected override void Initialize()
		{
			DependencyResolver.SetResolver(new CustomDependencyResolver());

			InitializeDb();
		}

		private void InitializeDb()
		{
			using (var database = DependencyResolver.Current.GetService<IShopDb>())
			{
				if (database.Exists())
				{
					return;
				}

				database.Create();
			}

			using (var context = DependencyResolver.Current.GetService<IShopUnitOfWork>())
			{
				context.CustomerRepository.Add(new Customer { Id = new Guid("5ebb39b8-d841-42c9-bdf6-3570204813e9"), Name = "Bill", Acquired = new DateTime(2011, 8, 20) });
				context.CustomerRepository.Add(new Customer { Id = new Guid("faccbeaf-ca71-419c-96fa-da93dfd05600"), Name = "Steve", Acquired = new DateTime(2011, 8, 23) });
				context.CustomerRepository.Add(new Customer { Id = new Guid("6c280ff9-1b59-47b1-9f95-c48b7ccb3012"), Name = "John", Acquired = new DateTime(2011, 8, 24) });

				context.Commit();
			}
		}
	}
}